package com.example.datagramsocket

import android.widget.Toast
import com.binyouwei.udp_lib.factory.DirectBroadcastFactory
import com.example.datagramsocket.base.BaseActivity
import com.example.datagramsocket.databinding.ActivityDirectBroadcastBinding
import com.example.datagramsocket.utils.MMKVCache

class DirectBroadcastActivity : BaseActivity<ActivityDirectBroadcastBinding>() {
    val TAG = javaClass.simpleName
    val mFactory by lazy { DirectBroadcastFactory() }

    override fun initView() {
        mBinding.apply {
            mFactory.initUdp()
            targetIp.setText(MMKVCache.getString(TAG))

            sureBtn.setOnClickListener {
                if (targetIp.text.isEmpty()) {
                    Toast.makeText(this@DirectBroadcastActivity, "请输入目标IP", Toast.LENGTH_SHORT)
                        .show()
                    return@setOnClickListener
                }
                val ip = targetIp.text.toString()
                MMKVCache.putString(TAG, ip)
                mFactory.onReceiveMessageListener(ip) {
                    this@DirectBroadcastActivity.runOnUiThread {
                        receiveMessage.text = it
                    }
                }
            }
            sendBtn.setOnClickListener {
                val message = sendMessage.text.toString()
                if (message.isEmpty()) {
                    Toast.makeText(
                        this@DirectBroadcastActivity,
                        "请输入发送消息",
                        Toast.LENGTH_SHORT
                    ).show()
                    return@setOnClickListener
                }
                mFactory.sendMessage(targetIp.text.toString(), message)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mFactory.destroyUdp()
    }

}